package {
import flash.events.Event;
import flash.net.FileReference;
import flash.net.FileReferenceList;
import flash.net.URLRequest;

import mx.collections.ArrayCollection;
import mx.utils.ObjectProxy;
public class FileUpload extends FileReferenceList {
	
	private var uploadURL:URLRequest;
	private var uploadFiles:ArrayCollection;
	public static var LIST_COMPLETE:String = "listComplete";
	public static var UPLOAD_ALL_FILE_COMPLETE:String = "uploadAllFileComplete"
	
	public function FileUpload(requestUrl:String, requestParamString:String) {
		uploadURL = new URLRequest();
		uploadURL.url = requestUrl;
		uploadURL.data = requestParamString;
		this.addEventListener(Event.SELECT, selectHandler);
	}
	
	public function upload():void {
		var file:FileReference;
		for (var i:uint = 0; i < uploadFiles.length; i++) {
			file = FileReference(uploadFiles[i].fileReference);
			file.upload(uploadURL);
		}
		doOnUploadAllFileComplete();
	}
	
	public function clear():void {
		uploadFiles = new ArrayCollection();
		doOnListComplete();
	}
	
	private function selectHandler(event:Event):void {
		uploadFiles = new ArrayCollection();
		var file:FileReference;
		for (var i:uint = 0; i < fileList.length; i++) {
			file = FileReference(fileList[i]);
			addFile(file);
		}
		doOnListComplete();
	}
	
	private function addFile(file:FileReference):void {
		var fileDetail:Object = new ObjectProxy();
		fileDetail.fileName = file.name;
		fileDetail.fileType = file.type;
		fileDetail.fileSize = int(file.size / 1024) + 1;
		fileDetail.fileReference = file;
		uploadFiles.addItem(fileDetail);
	}
	
	// 分发文件选择完成事件
	public function doOnListComplete():void {
        var event:Event = new Event(LIST_COMPLETE);
        dispatchEvent(event);
    }
    
    public function doOnUploadAllFileComplete():void {
    	var event:Event = new Event(UPLOAD_ALL_FILE_COMPLETE);
    	dispatchEvent(event);
    }
	
	private function removeFile(file:FileReference):void {
		for (var i:uint = 0; i < uploadFiles.length; i++) {
			if (uploadFiles[i].fileName == file.name) {
				uploadFiles.removeItemAt(i);
                return;
			}
		}
	}
	
	public function getUploadFiles():ArrayCollection {
		return uploadFiles;
	}
}
}
